package com.kzw.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;

import my.bean.Msg;
import my.mvc.Annotation.JSON;
import my.mvc.MultipartRequest;
import my.mvc.RequestContext;

/**
 * 文件上传接口
 */
public class FileAction {

	// 禁止上传的文件类型: .jsp, .exe
	private String[] forbidSuffix = { "jsp", "exe" };
	private DateFormat df = new SimpleDateFormat("yyyyMM");
	private List<String> allowList = null;

	/**
	 * layedit图片上传接口（单文件上传）
	 */
	@JSON
	public Msg upload(RequestContext rc) throws IOException {
		String category = rc.param("category", "other");
		Msg msg = new Msg();
		boolean flag = true;

		MultipartRequest req = (MultipartRequest) rc.request();
		File file = req.getFile("file");

		if (file != null) {
			String fname = file.getName();
			String ext = FilenameUtils.getExtension(fname);

			// 是否允许上传
			if (!canUpload(fname, allowList))
				flag = false;

			// 文件上传，文件名：类型+年月
			File dir = new File(RequestContext.root(), "upload");
			if (!dir.exists()) {
				FileUtils.forceMkdir(dir);
			}

			String path = category + "/" + df.format(new Date());
			File dir2 = new File(dir, path);
			if (!dir2.exists()) {
				FileUtils.forceMkdir(dir2);
			}
			
			
			String fid = RandomStringUtils.randomNumeric(8);
			String newfname = fid + "." + ext;
			File newfile = new File(dir2, newfname);

			FileInputStream is = new FileInputStream(file);
			FileOutputStream os = new FileOutputStream(newfile);

			IOUtils.copy(is, os);
			is.close();
			os.close();

			Map<String, Object> sub = new LinkedHashMap<String, Object>();
			sub.put("id", fid); // 新的文件名
			sub.put("ext", ext);
			sub.put("size", file.length());
			sub.put("title", fname); // 原来的文件名
			sub.put("src", rc.contextPath() + "/upload/" + path + "/" + newfname);

			msg = new Msg(true, 0, "文件上传成功！");
			msg.setData(sub);
		} else {
			msg = new Msg(false, 1, "没有文件上传！");
		}

		if (!flag) {
			msg = new Msg(false, 2, "非法文件！");
		}

		return msg;
	}

	/**
	 * 是否允许访问
	 */
	public boolean canUpload(String fname, List<String> allowList) {
		// 文件是否有后缀名
		String ext = FilenameUtils.getExtension(fname);
		if (ext.equals(""))
			return false;
		// 如果是禁止访问类型
		if (Arrays.asList(forbidSuffix).contains(ext)) {
			return false;
		}
		// 如果没有设置allow_perm，则默认开放
		if (allowList == null || allowList.size() == 0) {
			return true;
		}
		// 允许访问
		if (allowList.contains(ext)) {
			return true;
		}
		return false;
	}

}
